/**create by liuhua at 2019年5月23日 上午10:08:25**/
package com.star.truffle.gateway.filter;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

import java.net.URI;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;

import reactor.core.publisher.Mono;

public class RewriteGatewayFilter implements GatewayFilter, Ordered{

  private String routeId;
  private String realPath;
  
  public RewriteGatewayFilter(String routeId, String realPath) {
    this.routeId = routeId;
    this.realPath = realPath;
  }
  
  @Override
  public int getOrder() {
    return -100;
  }

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    URI uri = UriComponentsBuilder.fromHttpUrl(realPath).build().toUri();
    ServerHttpRequest newRequest = request.mutate().uri(uri).build();
    Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
    Route route2 = Route.async()
        .asyncPredicate(route.getPredicate())
        .filters(route.getFilters())
        .id(routeId)
        .order(route.getOrder())
        .uri(realPath)
        .build();
    exchange.getAttributes().put(GATEWAY_ROUTE_ATTR, route2);
    
    return chain.filter(exchange.mutate().request(newRequest).build());
  }

}
